/************************************************************
  *  * EaseMob CONFIDENTIAL 
  * __________________ 
  * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved. 
  *  
  * NOTICE: All information contained herein is, and remains 
  * the property of EaseMob Technologies.
  * Dissemination of this information or reproduction of this material 
  * is strictly forbidden unless prior written permission is obtained
  * from EaseMob Technologies.
  */

#import "ChatListViewController.h"
#import "SRRefreshView.h"
#import "ChatListCell.h"
#import "EMSearchBar.h"
#import "NSDate+Category.h"
#import "RealtimeSearchUtil.h"
#import "ChatViewController.h"
#import "EMSearchDisplayController.h"
#import "ConvertToCommonEmoticonsHelper.h"
#import "RobotManager.h"
#import "UserProfileManager.h"
#import "RobotChatViewController.h"
#import "GroupListViewController.h"
#import "ApplyViewController.h"
#import "ChineseToPinyin.h"
#import "AddFriendViewController.h"
#import "ChatroomListViewController.h"
#import "RobotListViewController.h"
#import "UIImageView+WebCache.h"
#import "KxMenu.h"
#import "CreateGroupViewController.h"
#import "AddFriendViewController.h"
#import "MyBuddy.h"
#import "Utils.h"
#import "Config.h"
#import "MyloginViewController.h"
#import "MyConversation.h"

@implementation MyConversation (search)

//根据用户昵称,环信机器人名称,群名称进行搜索
- (NSString*)showName
{
//    if (self.conversationType == eConversationTypeChat) {
//        if ([[RobotManager sharedInstance] isRobotWithUsername:self.chatter]) {
//            return [[RobotManager sharedInstance] getRobotNickWithUsername:self.chatter];
//        }
//        return [[UserProfileManager sharedInstance] getNickNameWithUsername:self.chatter];
//    } else if (self.conversationType == eConversationTypeGroupChat) {
//        if ([self.ext objectForKey:@"groupSubject"] || [self.ext objectForKey:@"isPublic"]) {
//           return [self.ext objectForKey:@"groupSubject"];
//        }
//    }
    return self.nickname;
}

@end

@implementation MyBuddy (search)

//根据用户昵称进行搜索
- (NSString*)showName
{
    return self.nickname;
}

@end

@interface ChatListViewController ()<UITableViewDelegate,UITableViewDataSource, UISearchDisplayDelegate,SRRefreshDelegate, UISearchBarDelegate, UIActionSheetDelegate, BaseTableCellDelegate,IChatManagerDelegate,ChatViewControllerDelegate>
{
    NSIndexPath *_currentLongPressIndex; //迁移过来
}

@property (strong, nonatomic) NSMutableArray        *dataSource;

@property (strong, nonatomic) NSMutableArray        *dataUsers;

@property (strong, nonatomic) UITableView           *tableView;
@property (nonatomic, strong) EMSearchBar           *searchBar;
@property (nonatomic, strong) SRRefreshView         *slimeView;
@property (nonatomic, strong) UIView                *networkStateView;

@property (strong, nonatomic) EMSearchDisplayController *searchController;

/*
 改造之
 */
@property  UIButton *baby_btn;
@property  UIButton *much_btn;

@property UIView *headerView;
@property NSUInteger selected_index;

@property UIView *selected_line;

/*
 * 迁移过来
 */
@property (strong, nonatomic) NSMutableArray *contactsSource;
@property (strong, nonatomic) NSMutableArray *dataSource1;
@property (strong, nonatomic) NSMutableArray *sectionTitles;

@property (strong, nonatomic) UILabel *unapplyCountLabel;
@property (strong, nonatomic) UITableView *tableView1;
@property (strong, nonatomic) EMSearchBar *searchBar1;
@property (strong, nonatomic) SRRefreshView *slimeView1;
@property (strong, nonatomic) GroupListViewController *groupController;

@property (strong, nonatomic) EMSearchDisplayController *searchController1;

@property UIBarButtonItem *addFriendItem;
@property UIBarButtonItem *addChatItem;

@end

@implementation ChatListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _dataSource = [NSMutableArray array];
        _dataUsers = [NSMutableArray array];
        
        /*
         * 迁移过来
         */
        _dataSource1 = [NSMutableArray array];
        _contactsSource = [NSMutableArray array];
        _sectionTitles = [NSMutableArray array];
        [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:NO];
    [self removeEmptyConversationsFromDB];
    
    _selected_index = 1;
    [self customView];

    [self.view addSubview:self.searchBar];

    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.slimeView];
    [self networkStateView];

    [self searchController];
    
    /*
     * 迁移过来
     */
    
    self.searchBar1.frame = CGRectMake(0, 0, self.view.frame.size.width, 44);
    [self.view addSubview:self.searchBar1];
    [self searchController1];
    self.tableView1.frame = CGRectMake(0, self.searchBar1.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - self.searchBar1.frame.size.height);
    [self.view addSubview:self.tableView1];
    [self.tableView1 addSubview:self.slimeView1];
    
    [self reloadDataSource];
    // 环信UIdemo中有用到Parse, 加载用户好友个人信息
   // [[UserProfileManager sharedInstance] loadUserProfileInBackgroundWithBuddy:self.contactsSource saveToLoacal:YES completion:NULL];
    
    /*
     */
    [_tableView setHidden:NO];
    [_slimeView setHidden:NO];
    [_searchBar setHidden:NO];
    
    
    [_tableView1 setHidden:YES];
    [_slimeView1 setHidden:YES];
    [_searchBar1 setHidden:YES];

    UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [addButton setImage:[UIImage imageNamed:@"contact_add"] forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(addFriendAction) forControlEvents:UIControlEventTouchUpInside];
    _addFriendItem = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    
    UIButton *addChat = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [addChat setImage:[UIImage imageNamed:@"yellow_add"] forState:UIControlStateNormal];
    [addChat addTarget:self action:@selector(addChatAction:) forControlEvents:UIControlEventTouchUpInside];
    _addChatItem = [[UIBarButtonItem alloc] initWithCustomView:addChat];
    
    self.navigationItem.rightBarButtonItem = _addChatItem;
}

-(void)addChatAction:(UIButton*)sender
{
    NSArray *menuItems =
    @[
      
      [KxMenuItem menuItem:@"发起群聊"
                     image:[UIImage imageNamed:@"group_chat"]
                    target:self
                    action:@selector(createGroup:)],
      
      [KxMenuItem menuItem:@"添加莱友"
                     image:[UIImage imageNamed:@"peo_add"]
                    target:self
                    action:@selector(addFriend:)],
      ];
    CGRect frame = CGRectMake(sender.frame.origin.x, sender.frame.origin.y+10, sender.frame.size.width, sender.frame.size.height);
    [KxMenu showMenuInView:[UIApplication sharedApplication].keyWindow
                  fromRect:frame                 menuItems:menuItems];
}

-(void)createGroup:(id)sender
{
    if([[Config Instance]isCookie]){
        CreateGroupViewController *create = [[CreateGroupViewController alloc]init];
        [self.navigationController pushViewController:create animated:YES];
        create.hidesBottomBarWhenPushed = YES;
    }else{
        MyloginViewController *login = [MyloginViewController shareController];
        
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
    }
   
}

-(void)addFriend:(id)sender
{
    if([[Config Instance]isCookie]){
        AddFriendViewController *create = [[AddFriendViewController alloc]init];
        create.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:create animated:YES];
    }else{
        MyloginViewController *login = [MyloginViewController shareController];
        
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
    }
    
}

-(void)customView{
    
    self.navigationController.navigationBarHidden = NO;
    // self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    
    _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 170, 45)];
    
    [_headerView setBackgroundColor:[UIColor clearColor]];
    
    _much_btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 5, 85, 40)];
    [_much_btn setTitle:@"莱信" forState:UIControlStateNormal];
    _much_btn.titleLabel.font = [UIFont systemFontOfSize:20.0];
    
    [_much_btn addTarget:self action:@selector(chatListCallback:) forControlEvents:UIControlEventTouchUpInside];
    _baby_btn = [[UIButton alloc]initWithFrame:CGRectMake(85, 5, 85, 40)];
    [_baby_btn setTitle:@"莱友" forState:UIControlStateNormal];
    [_baby_btn addTarget:self action:@selector(contactCallback:) forControlEvents:UIControlEventTouchUpInside];
    _baby_btn.titleLabel.font = [UIFont systemFontOfSize:20.0];
    
    [_headerView addSubview:_much_btn];
    [_headerView addSubview:_baby_btn];
    
    self.navigationItem.titleView = _headerView;
    
    [self setBtnsStatus];
    
    _selected_line = [[UIView alloc]initWithFrame:CGRectMake(20.5, 38, 44, 0.5)];
    [_selected_line setBackgroundColor:UIColorMake(252, 74, 74)];
    [_headerView addSubview:_selected_line];
    
}
-(void)setBtnsStatus
{
    switch (_selected_index) {
        case 1:
        {
            //[_quan_btn setTitleColor:UIColorMake(252, 74, 74) forState:UIControlStateNormal];
            [_much_btn setTitleColor:UIColorMake(252, 74, 74) forState:UIControlStateNormal];
            [_baby_btn setTitleColor:UIColorMake(91, 91, 91) forState:UIControlStateNormal];
            [_selected_line setFrame:CGRectMake(20.5, 38, 44, .5)];
            
            break;
        }
        case 2:
        {
            [_much_btn setTitleColor:UIColorMake(91, 91, 91) forState:UIControlStateNormal];
            // [_quan_btn setTitleColor:UIColorMake(91, 91, 91) forState:UIControlStateNormal];
            [_baby_btn setTitleColor:UIColorMake(252, 74, 74) forState:UIControlStateNormal];
            [_selected_line setFrame:CGRectMake(106, 38, 44, .5)];
            self.navigationItem.rightBarButtonItem.enabled = YES;
            break;
        }
        default:
            break;
    }
}
- (void)chatListCallback:(id)sender {
    if(_selected_index ==1){
        return;
    }
    _selected_index =1;
    [self setBtnsStatus];
    /*
    [self.tableview2 headerBeginRefreshing];
    [self.view bringSubviewToFront:_tableview2];
    [self.view bringSubviewToFront:_pubButton];
     */
    [_tableView setHidden:NO];
    [_slimeView setHidden:NO];
    [_searchBar setHidden:NO];
    
    [_tableView1 setHidden:YES];
    [_slimeView1 setHidden:YES];
    [_searchBar1 setHidden:YES];
    
    self.navigationItem.rightBarButtonItem = _addChatItem;
}
- (void)contactCallback:(id)sender {
    if(_selected_index ==2){
        return;
    }
    _selected_index =2;
    [self setBtnsStatus];
    /*
    //[self.tableview3 headerBeginRefreshing];
    [self.view bringSubviewToFront:_tableview3];
     */
    [_tableView setHidden:YES];
    [_slimeView setHidden:YES];
    [_searchBar setHidden:YES];
    
    [_tableView1 setHidden:NO];
    [_slimeView1 setHidden:NO];
    [_searchBar1 setHidden:NO];
    self.navigationItem.rightBarButtonItem = _addFriendItem;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self refreshDataSource];
    [self registerNotifications];
    
    /*
     * 迁移过来
     */
    [self reloadApplyView];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self unregisterNotifications];
}

- (void)removeEmptyConversationsFromDB
{
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    NSMutableArray *needRemoveConversations;
    for (EMConversation *conversation in conversations) {
        if (!conversation.latestMessage || (conversation.conversationType == eConversationTypeChatRoom)) {
            if (!needRemoveConversations) {
                needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
            }
            
            [needRemoveConversations addObject:conversation.chatter];
        }
    }
    
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EaseMob sharedInstance].chatManager removeConversationsByChatters:needRemoveConversations
                                                             deleteMessages:YES
                                                                append2Chat:NO];
    }
}

- (void)removeChatroomConversationsFromDB
{
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    NSMutableArray *needRemoveConversations;
    for (EMConversation *conversation in conversations) {
        if (conversation.conversationType == eConversationTypeChatRoom) {
            if (!needRemoveConversations) {
                needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
            }
            
            [needRemoveConversations addObject:conversation.chatter];
        }
    }
    
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EaseMob sharedInstance].chatManager removeConversationsByChatters:needRemoveConversations
                                                             deleteMessages:YES
                                                                append2Chat:NO];
    }
}

#pragma mark - getter

- (SRRefreshView *)slimeView
{
    if (!_slimeView) {
        _slimeView = [[SRRefreshView alloc] init];
        _slimeView.delegate = self;
        _slimeView.upInset = 0;
        _slimeView.slimeMissWhenGoingBack = YES;
        _slimeView.slime.bodyColor = [UIColor grayColor];
        _slimeView.slime.skinColor = [UIColor grayColor];
        _slimeView.slime.lineWith = 1;
        _slimeView.slime.shadowBlur = 4;
        _slimeView.slime.shadowColor = [UIColor grayColor];
        _slimeView.backgroundColor = [UIColor whiteColor];
    }
    
    return _slimeView;
}

- (UISearchBar *)searchBar
{
    if (!_searchBar) {
        _searchBar = [[EMSearchBar alloc] initWithFrame: CGRectMake(0, 0, self.view.frame.size.width, 44)];
        _searchBar.delegate = self;
        
        _searchBar.placeholder = @"搜索";
        _searchBar.backgroundColor = UIColorMake(240, 240,240);
    }
    
    return _searchBar;
}

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.searchBar.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - self.searchBar.frame.size.height) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ChatListCell class] forCellReuseIdentifier:@"chatListCell"];
    }
    
    return _tableView;
}

- (EMSearchDisplayController *)searchController
{
    if (_searchController == nil) {
        _searchController = [[EMSearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
        _searchController.delegate = self;
        _searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        __weak ChatListViewController *weakSelf = self;
        [_searchController setCellForRowAtIndexPathCompletion:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            static NSString *CellIdentifier = @"ChatListCell";
            ChatListCell *cell = (ChatListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            
            // Configure the cell...
            if (cell == nil) {
                cell = [[ChatListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            
            MyConversation *conversation = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
            cell.name = conversation.nickname;
            if (conversation.conversation.conversationType == eConversationTypeChat) {
                //cell.name = [[RobotManager sharedInstance] getRobotNickWithUsername:conversation.chatter];
                //cell.placeholderImage = [UIImage imageNamed:@"chatListCellHead.png"];
                cell.imageURL = [NSURL URLWithString:conversation.pic];
            }
            else{
                NSString *imageName = @"group_logo";
                NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
                for (EMGroup *group in groupArray) {
                    if ([group.groupId isEqualToString:conversation.conversation.chatter]) {
                        cell.name = group.groupSubject;
                        imageName = group.isPublic ? @"group_logo" : @"group_logo";
                        break;
                    }
                }
                cell.placeholderImage = [UIImage imageNamed:imageName];
            }
            cell.detailMsg = [weakSelf subTitleMessageByConversation:conversation.conversation];
            cell.time = [weakSelf lastMessageTimeByConversation:conversation.conversation];
            cell.unreadCount = [weakSelf unreadMessageCountByConversation:conversation.conversation];
            if (indexPath.row % 2 == 1) {
                cell.contentView.backgroundColor = RGBACOLOR(246, 246, 246, 1);
            }else{
                cell.contentView.backgroundColor = [UIColor whiteColor];
            }
            return cell;
        }];
        
        [_searchController setHeightForRowAtIndexPathCompletion:^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            return [ChatListCell tableView:tableView heightForRowAtIndexPath:indexPath];
        }];
        
        [_searchController setDidSelectRowAtIndexPathCompletion:^(UITableView *tableView, NSIndexPath *indexPath) {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            [weakSelf.searchController.searchBar endEditing:YES];
            
            MyConversation *conversation = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
            ChatViewController *chatController;
            if ([[RobotManager sharedInstance] isRobotWithUsername:conversation.conversation.chatter]) {
                chatController = [[RobotChatViewController alloc] initWithChatter:conversation.conversation.chatter
                                                                 conversationType:conversation.conversation.conversationType];
                chatController.title = [[RobotManager sharedInstance] getRobotNickWithUsername:conversation.conversation.chatter];
            }else {
                chatController = [[ChatViewController alloc] initWithChatter:conversation.conversation.chatter
                                                            conversationType:conversation.conversation.conversationType];
                chatController.title = [conversation nickname];
            }
            chatController.hidesBottomBarWhenPushed = YES;
            [weakSelf.navigationController pushViewController:chatController animated:YES];
        }];
    }
    
    return _searchController;
}

- (UIView *)networkStateView
{
    if (_networkStateView == nil) {
        _networkStateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 44)];
        _networkStateView.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:199 / 255.0 blue:199 / 255.0 alpha:0.5];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (_networkStateView.frame.size.height - 20) / 2, 20, 20)];
        imageView.image = [UIImage imageNamed:@"messageSendFail"];
        [_networkStateView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + 5, 0, _networkStateView.frame.size.width - (CGRectGetMaxX(imageView.frame) + 15), _networkStateView.frame.size.height)];
        label.font = [UIFont systemFontOfSize:15.0];
        label.textColor = [UIColor grayColor];
        label.backgroundColor = [UIColor clearColor];
        label.text = NSLocalizedString(@"network.disconnection", @"Network disconnection");
        [_networkStateView addSubview:label];
    }
    
    return _networkStateView;
}

#pragma mark - private

- (NSMutableArray *)loadDataSource
{
    NSMutableArray *ret = [NSMutableArray array];
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];

    NSArray* sorte = [conversations sortedArrayUsingComparator:
           ^(EMConversation *obj1, EMConversation* obj2){
               EMMessage *message1 = [obj1 latestMessage];
               EMMessage *message2 = [obj2 latestMessage];
               if(message1.timestamp > message2.timestamp) {
                   return(NSComparisonResult)NSOrderedAscending;
               }else {
                   return(NSComparisonResult)NSOrderedDescending;
               }
           }];
    
    //ret = [[NSMutableArray alloc] initWithArray:sorte];
    for (EMConversation *coverst in sorte) {
        MyConversation *myconvert = [MyConversation new];
        myconvert.conversation = coverst;
        [myconvert loadInfoByUsername];
        [ret addObject:myconvert];
    }
    return ret;
}

// 得到最后消息时间
-(NSString *)lastMessageTimeByConversation:(EMConversation *)conversation
{
    NSString *ret = @"";
    EMMessage *lastMessage = [conversation latestMessage];;
    if (lastMessage) {
        ret = [NSDate formattedTimeFromTimeInterval:lastMessage.timestamp];
    }
    
    return ret;
}

// 得到未读消息条数
- (NSInteger)unreadMessageCountByConversation:(EMConversation *)conversation
{
    NSInteger ret = 0;
    ret = conversation.unreadMessagesCount;
    
    return  ret;
}

// 得到最后消息文字或者类型
-(NSString *)subTitleMessageByConversation:(EMConversation *)conversation
{
    NSString *ret = @"";
    EMMessage *lastMessage = [conversation latestMessage];
    if (lastMessage) {
        id<IEMMessageBody> messageBody = lastMessage.messageBodies.lastObject;
        switch (messageBody.messageBodyType) {
            case eMessageBodyType_Image:{
                ret = NSLocalizedString(@"message.image1", @"[image]");
            } break;
            case eMessageBodyType_Text:{
                // 表情映射。
                NSString *didReceiveText = [ConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                if ([[RobotManager sharedInstance] isRobotMenuMessage:lastMessage]) {
                    ret = [[RobotManager sharedInstance] getRobotMenuMessageDigest:lastMessage];
                } else {
                    ret = didReceiveText;
                }
            } break;
            case eMessageBodyType_Voice:{
                ret = NSLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case eMessageBodyType_Location: {
                ret = NSLocalizedString(@"message.location1", @"[location]");
            } break;
            case eMessageBodyType_Video: {
                ret = NSLocalizedString(@"message.video1", @"[video]");
            } break;
            default: {
            } break;
        }
    }
    
    return ret;
}

#pragma mark - TableViewDelegate & TableViewDatasource

-(UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == _tableView){
    static NSString *identify = @"chatListCell";
    ChatListCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    
    if (!cell) {
        cell = [[ChatListCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identify];
    }
    MyConversation *conversation = [self.dataSource objectAtIndex:indexPath.row];
    cell.name = conversation.conversation.chatter;
    if (conversation.conversation.conversationType == eConversationTypeChat) {
        //cell.name = [[RobotManager sharedInstance] getRobotNickWithUsername:conversation.chatter];
        //cell.placeholderImage = [UIImage imageNamed:@"chatListCellHead.png"];
        //NSDictionary *info = [self.dataUsers objectAtIndex:indexPath.row];
        //debugLog(@"info:%@",self.dataUsers);
        cell.name = conversation.nickname;
//        if([info objectForKey:@"pic"]!=[NSNull null]){
//            cell.imageURL = [NSURL URLWithString:[info objectForKey:@"pic"]];
//        }
        cell.imageURL = [NSURL URLWithString:conversation.pic];
        debugLog(@"pic:%@",conversation.pic);
        cell.placeholderImage = [UIImage imageNamed:@"default_avatar"];
       //  [cell.imageView sd_setImageWithURL:[NSURL URLWithString:conversation.pic] placeholderImage:[UIImage imageNamed:@"default_avatar"]];
    }
    else{
        NSString *imageName = @"group_logo";
        if (![conversation.conversation.ext objectForKey:@"groupSubject"] || ![conversation.conversation.ext objectForKey:@"isPublic"])
        {
            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:conversation.conversation.chatter]) {
                    cell.name = group.groupSubject;
                    imageName = group.isPublic ? @"group_logo" : @"group_logo";

                    NSMutableDictionary *ext = [NSMutableDictionary dictionaryWithDictionary:conversation.conversation.ext];
                    [ext setObject:group.groupSubject forKey:@"groupSubject"];
                    [ext setObject:[NSNumber numberWithBool:group.isPublic] forKey:@"isPublic"];
                    conversation.conversation.ext = ext;
                    break;
                }
            }
        }
        else
        {
            cell.name = [conversation.conversation.ext objectForKey:@"groupSubject"];
            imageName = [[conversation.conversation.ext objectForKey:@"isPublic"] boolValue] ? @"group_logo" : @"group_logo";
        }
        cell.placeholderImage = [UIImage imageNamed:imageName];
    }
    cell.detailMsg = [self subTitleMessageByConversation:conversation.conversation];
    cell.time = [self lastMessageTimeByConversation:conversation.conversation];
    cell.unreadCount = [self unreadMessageCountByConversation:conversation.conversation];
    if (indexPath.row % 2 == 1) {
        cell.contentView.backgroundColor = RGBACOLOR(246, 246, 246, 1);
    }else{
        cell.contentView.backgroundColor = [UIColor whiteColor];
    }
    return cell;
    }else{
        BaseTableViewCell *cell;
        
        if (indexPath.section == 0 && indexPath.row == 0) {
            cell = (BaseTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"FriendCell"];
            if (cell == nil) {
                cell = [[BaseTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FriendCell"];
            }
            
            cell.imageView.image = [UIImage imageNamed:@"friend_new"];
            cell.textLabel.text = NSLocalizedString(@"title.apply", @"Application and notification");
            [cell addSubview:self.unapplyCountLabel];
        }
        else{
            static NSString *CellIdentifier = @"ContactListCell";
            cell = (BaseTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            // Configure the cell...
            if (cell == nil) {
                cell = [[BaseTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                cell.delegate = self;
            }
            
            cell.indexPath = indexPath;
            if (indexPath.section == 0 && indexPath.row == 1) {
                cell.imageView.image = [UIImage imageNamed:@"group_icon"];
                cell.username = @"群组";
                debugLog(cell.username);
            }
            /*
            else if (indexPath.section == 0 && indexPath.row == 2) {
                cell.imageView.image = [UIImage imageNamed:@"groupPublicHeader"];
                cell.username = NSLocalizedString(@"title.chatroomlist",@"chatroom list");
            }
            else if (indexPath.section == 0 && indexPath.row == 3) {
                cell.imageView.image = [UIImage imageNamed:@"groupPublicHeader"];
                cell.username = NSLocalizedString(@"title.robotlist",@"robot list");
            }*/
            else{
                MyBuddy *buddy = [[self.dataSource1 objectAtIndex:(indexPath.section - 1)] objectAtIndex:indexPath.row];
                //cell.imageView.image = [UIImage imageNamed:@"chatListCellHead.png"];
                //cell.username = buddy.nickname;
                cell.textLabel.text = buddy.nickname;
                [cell.imageView sd_setImageWithURL:[NSURL URLWithString:buddy.pic] placeholderImage:[UIImage imageNamed:@"default_avatar"]];
            }
        }
        
        return cell;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(tableView == _tableView){
        return  self.dataSource.count;
    }else{
        if (section == 0) {
            return 2;
            //        return 1;
        }
        
        return [[self.dataSource1 objectAtIndex:(section - 1)] count];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == _tableView){
        return [ChatListCell tableView:tableView heightForRowAtIndexPath:indexPath];
    }else{
        return 60;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == _tableView){
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MyConversation *conversation = [self.dataSource objectAtIndex:indexPath.row];
    
    ChatViewController *chatController;
    NSString *title = conversation.conversation.chatter;
    if (conversation.conversation.conversationType != eConversationTypeChat) {
        if ([[conversation.conversation.ext objectForKey:@"groupSubject"] length])
        {
            title = [conversation.conversation.ext objectForKey:@"groupSubject"];
        }
        else
        {
            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:conversation.conversation.chatter]) {
                    title = group.groupSubject;
                    break;
                }
            }
        }
    } else if (conversation.conversation.conversationType == eConversationTypeChat) {
        title = [[UserProfileManager sharedInstance] getNickNameWithUsername:conversation.conversation.chatter];
    }
    
    NSString *chatter = conversation.conversation.chatter;
    if ([[RobotManager sharedInstance] isRobotWithUsername:chatter]) {
        chatController = [[RobotChatViewController alloc] initWithChatter:chatter
                                                    conversationType:conversation.conversation.conversationType];
        chatController.title = [[RobotManager sharedInstance] getRobotNickWithUsername:chatter];
    }else {
        chatController = [[ChatViewController alloc] initWithChatter:chatter
                                                    conversationType:conversation.conversation.conversationType];
        chatController.title = conversation.nickname;
    }
    
    chatController.delelgate = self;
        chatController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chatController animated:YES];
    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                ApplyViewController *apply = [ApplyViewController shareController];
                apply.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:apply animated:YES];
            }
            else if (indexPath.row == 1)
            {
                if (_groupController == nil) {
                    _groupController = [[GroupListViewController alloc] initWithStyle:UITableViewStylePlain];
                }
                else{
                    [_groupController reloadDataSource];
                }
                _groupController.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:_groupController animated:YES];
            }
            else if (indexPath.row == 2)
            {
                ChatroomListViewController *controller = [[ChatroomListViewController alloc] initWithStyle:UITableViewStylePlain];
                controller.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:controller animated:YES];
            }
            else if (indexPath.row == 3)
            {
                RobotListViewController *controller = [[RobotListViewController alloc] initWithStyle:UITableViewStylePlain];
                controller.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:controller animated:YES];
            }
        }
        else{
            MyBuddy *buddy = [[self.dataSource1 objectAtIndex:(indexPath.section - 1)] objectAtIndex:indexPath.row];
            NSDictionary *loginInfo = [[[EaseMob sharedInstance] chatManager] loginInfo];
            NSString *loginUsername = [loginInfo objectForKey:kSDKUsername];
            if (loginUsername && loginUsername.length > 0) {
                if ([loginUsername isEqualToString:buddy.buddy.username]) {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:NSLocalizedString(@"friend.notChatSelf", @"can't talk to yourself") delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
                    [alertView show];
                    
                    return;
                }
            }
            
            ChatViewController *chatVC = [[ChatViewController alloc] initWithChatter:buddy.buddy.username isGroup:NO];
//            chatVC.title = [[UserProfileManager sharedInstance] getNickNameWithUsername:buddy.username];
            chatVC.title = buddy.nickname;
            chatVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:chatVC animated:YES];
        }
    }
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == _tableView){
    return YES;
    }else{
        if (indexPath.section == 0) {
            return NO;
            [self isViewLoaded];
        }
        return YES;
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(tableView ==_tableView){
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        EMConversation *converation = [self.dataSource objectAtIndex:indexPath.row];
        [[EaseMob sharedInstance].chatManager removeConversationByChatter:converation.chatter deleteMessages:YES append2Chat:YES];
        [self.dataSource removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    }else{
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            NSDictionary *loginInfo = [[[EaseMob sharedInstance] chatManager] loginInfo];
            NSString *loginUsername = [loginInfo objectForKey:kSDKUsername];
            MyBuddy *buddy = [[self.dataSource1 objectAtIndex:(indexPath.section - 1)] objectAtIndex:indexPath.row];
            if ([buddy.buddy.username isEqualToString:loginUsername]) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:NSLocalizedString(@"friend.notDeleteSelf", @"can't delete self") delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
                [alertView show];
                
                return;
            }
            
            EMError *error = nil;
            [[EaseMob sharedInstance].chatManager removeBuddy:buddy.buddy.username removeFromRemote:YES error:&error];
            if (!error) {
                [[EaseMob sharedInstance].chatManager removeConversationByChatter:buddy.buddy.username deleteMessages:YES append2Chat:YES];
                
                [tableView beginUpdates];
                [[self.dataSource1 objectAtIndex:(indexPath.section - 1)] removeObjectAtIndex:indexPath.row];
                [self.contactsSource removeObject:buddy];
                [tableView  deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                [tableView  endUpdates];
            }
            else{
                [self showHint:[NSString stringWithFormat:NSLocalizedString(@"deleteFailed", @"Delete failed:%@"), error.description]];
                [tableView reloadData];
            }
        }
    }
}


#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
//    self.navigationController
    if(searchBar == _searchBar){
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;

    [searchBar setShowsCancelButton:YES animated:YES];
    
    return YES;
    }else{
        [searchBar setShowsCancelButton:YES animated:YES];
        
        return YES;
    }
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if(searchBar == _searchBar){
    __weak typeof(self) weakSelf = self;
    [[RealtimeSearchUtil currentUtil] realtimeSearchWithSource:self.dataSource searchText:(NSString *)searchText collationStringSelector:@selector(showName) resultBlock:^(NSArray *results) {
        if (results) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.searchController.resultsSource removeAllObjects];
                [weakSelf.searchController.resultsSource addObjectsFromArray:results];
                [weakSelf.searchController.searchResultsTableView reloadData];
            });
        }
    }];
    }else{
        __weak typeof(self) weakSelf = self;
        [[RealtimeSearchUtil currentUtil] realtimeSearchWithSource:self.contactsSource searchText:(NSString *)searchText collationStringSelector:@selector(showName) resultBlock:^(NSArray *results) {
            if (results) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.searchController1.resultsSource removeAllObjects];
                    [weakSelf.searchController1.resultsSource addObjectsFromArray:results];
                    [weakSelf.searchController1.searchResultsTableView reloadData];
                });
            }
        }];

    }
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @"";
    [[RealtimeSearchUtil currentUtil] realtimeSearchStop];
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];
}

#pragma mark - scrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(!_slimeView.isHidden){
        [_slimeView scrollViewDidScroll];
    }
    if(!_slimeView1.isHidden){
        [_slimeView1 scrollViewDidScroll];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if(!_slimeView.isHidden){
    [_slimeView scrollViewDidEndDraging];
    }
    if(!_slimeView1.isHidden){
        [_slimeView1 scrollViewDidEndDraging];
    }
}

#pragma mark - slimeRefresh delegate
//刷新消息列表
- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    if(refreshView == _slimeView){
        [self refreshDataSource];
        [_slimeView endRefresh];
    }else{
        __weak ChatListViewController *weakSelf = self;
        [[[EaseMob sharedInstance] chatManager] asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
            [weakSelf.slimeView1 endRefresh];
        } onQueue:nil];
    }
}

#pragma mark - IChatMangerDelegate

-(void)didUnreadMessagesCountChanged
{
    [self refreshDataSource];
}

- (void)didUpdateGroupList:(NSArray *)allGroups error:(EMError *)error
{
    [self refreshDataSource];
}

#pragma mark - registerNotifications
-(void)registerNotifications{
    [self unregisterNotifications];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

-(void)unregisterNotifications{
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

- (void)dealloc{
    [self unregisterNotifications];
    /*
     *迁移过来
     */
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

#pragma mark - public

-(void)refreshDataSource
{
    self.dataSource = [self loadDataSource];
    /*
    [self.dataUsers removeAllObjects];
    for (EMConversation *conversation in self.dataSource) {
        if(conversation.conversationType == eConversationTypeChat) {
            NSString *chat = conversation.chatter;
            NSString * url = [NSString stringWithFormat:@"%@%@/uid/%@",SERVER_URL_NEW,kMyInfomartion,chat];
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]
                                                 options:NSDataReadingMappedIfSafe
                                                   error:nil];
            if (data) {
                NSDictionary *userInfoDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                
                if (!userInfoDic) {
                    debugLog(@"数据获取格式不对！");
                } else {
                    debugLog(@"%@",[userInfoDic objectForKey:@"result"]);
                    [self.dataUsers addObject:[userInfoDic objectForKey:@"result"]];
                }
            }else{
                debugLog(@"用户不存在~");
            }
        }else{
            debugLog(@"非单聊");
            [self.dataUsers addObject:conversation];
        }
        
    }*/
    [_tableView reloadData];
    [self hideHud];
}

- (void)isConnect:(BOOL)isConnect{
    if (!isConnect) {
        _tableView.tableHeaderView = _networkStateView;
    }
    else{
        _tableView.tableHeaderView = nil;
    }

}

- (void)networkChanged:(EMConnectionState)connectionState
{
    if (connectionState == eEMConnectionDisconnected) {
        _tableView.tableHeaderView = _networkStateView;
    }
    else{
        _tableView.tableHeaderView = nil;
    }
}

- (void)willReceiveOfflineMessages{
    NSLog(NSLocalizedString(@"message.beginReceiveOffine", @"Begin to receive offline messages"));
}

- (void)didReceiveOfflineMessages:(NSArray *)offlineMessages
{
    [self refreshDataSource];
}

- (void)didFinishedReceiveOfflineMessages{
    NSLog(NSLocalizedString(@"message.endReceiveOffine", @"End to receive offline messages"));
}

#pragma mark - ChatViewControllerDelegate

// 根据环信id得到要显示头像路径，如果返回nil，则显示默认头像
- (NSString *)avatarWithChatter:(NSString *)chatter{
//    return @"http://img0.bdstatic.com/img/image/shouye/jianbihua0525.jpg";
    debugLog(@"chatter:%@",chatter);
    for (MyConversation *conver in self.dataSource) {
        debugLog(@"chatter1:%@",conver.conversation.chatter);
        if([conver.conversation.chatter isEqualToString:chatter]){
            
            return conver.pic;
        }
    }
    return nil;
}

// 根据环信id得到要显示用户名，如果返回nil，则默认显示环信id
- (NSString *)nickNameWithChatter:(NSString *)chatter{
    for (MyConversation *conver in self.dataSource) {
        if([conver.conversation.chatter isEqualToString:chatter]){
            return conver.nickname;
        }
    }
    return chatter;
}


/*
 迁移过来
 */
- (UISearchBar *)searchBar1
{
    if (_searchBar1 == nil) {
        _searchBar1 = [[EMSearchBar alloc] init];
        _searchBar1.delegate = self;
        _searchBar1.placeholder = @"搜索";
        _searchBar1.backgroundColor = UIColorMake(240, 240,240);
    }
    
    return _searchBar1;
}

- (UILabel *)unapplyCountLabel
{
    if (_unapplyCountLabel == nil) {
        _unapplyCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(36, 5, 20, 20)];
        _unapplyCountLabel.textAlignment = NSTextAlignmentCenter;
        _unapplyCountLabel.font = [UIFont systemFontOfSize:11];
        _unapplyCountLabel.backgroundColor = [UIColor redColor];
        _unapplyCountLabel.textColor = [UIColor whiteColor];
        _unapplyCountLabel.layer.cornerRadius = _unapplyCountLabel.frame.size.height / 2;
        _unapplyCountLabel.hidden = YES;
        _unapplyCountLabel.clipsToBounds = YES;
    }
    
    return _unapplyCountLabel;
}

- (SRRefreshView *)slimeView1
{
    if (_slimeView1 == nil) {
        _slimeView1 = [[SRRefreshView alloc] init];
        _slimeView1.delegate = self;
        _slimeView1.upInset = 0;
        _slimeView1.slimeMissWhenGoingBack = YES;
        _slimeView1.slime.bodyColor = [UIColor grayColor];
        _slimeView1.slime.skinColor = [UIColor grayColor];
        _slimeView1.slime.lineWith = 1;
        _slimeView1.slime.shadowBlur = 4;
        _slimeView1.slime.shadowColor = [UIColor grayColor];
    }
    
    return _slimeView1;
}

- (UITableView *)tableView1
{
    if (_tableView1 == nil)
    {
        _tableView1 = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView1.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView1.backgroundColor = [UIColor whiteColor];
        _tableView1.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        _tableView1.delegate = self;
        _tableView1.dataSource = self;
        _tableView1.tableFooterView = [[UIView alloc] init];
    }
    
    return _tableView1;
}

- (EMSearchDisplayController *)searchController1
{
    if (_searchController1 == nil) {
        _searchController1 = [[EMSearchDisplayController alloc] initWithSearchBar:self.searchBar1 contentsController:self];
        _searchController1.delegate = self;
        _searchController1.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        __weak ChatListViewController *weakSelf = self;
        [_searchController1 setCellForRowAtIndexPathCompletion:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            static NSString *CellIdentifier = @"ContactListCell";
            BaseTableViewCell *cell = (BaseTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            
            // Configure the cell...
            if (cell == nil) {
                cell = [[BaseTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            
            MyBuddy *buddy = [weakSelf.searchController1.resultsSource objectAtIndex:indexPath.row];
            //cell.username = buddy.buddy.username;
            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:buddy.pic] placeholderImage:[UIImage imageNamed:@"default_avatar"]];
            cell.textLabel.text = buddy.nickname;
            
            return cell;
        }];
        
        [_searchController1 setHeightForRowAtIndexPathCompletion:^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            return 50;
        }];
        
        [_searchController1 setDidSelectRowAtIndexPathCompletion:^(UITableView *tableView, NSIndexPath *indexPath) {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            
            MyBuddy *buddy = [weakSelf.searchController1.resultsSource objectAtIndex:indexPath.row];
            NSDictionary *loginInfo = [[[EaseMob sharedInstance] chatManager] loginInfo];
            NSString *loginUsername = [loginInfo objectForKey:kSDKUsername];
            if (loginUsername && loginUsername.length > 0) {
                if ([loginUsername isEqualToString:buddy.buddy.username]) {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:NSLocalizedString(@"friend.notChatSelf", @"can't talk to yourself") delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
                    [alertView show];
                    
                    return;
                }
            }
            
            [weakSelf.searchController1.searchBar endEditing:YES];
            ChatViewController *chatVC = [[ChatViewController alloc] initWithChatter:buddy.buddy.username isGroup:NO];
//            chatVC.title = [[UserProfileManager sharedInstance] getNickNameWithUsername:buddy.username];
            chatVC.title = buddy.nickname;
            chatVC.hidesBottomBarWhenPushed = YES;
            [weakSelf.navigationController pushViewController:chatVC animated:YES];
        }];
    }
    
    return _searchController1;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    if(tableView ==_tableView1){
        return [self.dataSource1 count] + 1;
    }else{
        return 1;
    }
}



#pragma mark - Table view delegate


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(tableView==_tableView1){
        if (section == 0 || [[self.dataSource1 objectAtIndex:(section - 1)] count] == 0)
        {
        return 0;
        }
        else{
        return 22;
        }
    }else{
        return 0.0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(tableView == _tableView1){
    if (section == 0 || [[self.dataSource1 objectAtIndex:(section - 1)] count] == 0)
    {
        return nil;
    }
    
    UIView *contentView = [[UIView alloc] init];
    [contentView setBackgroundColor:[UIColor colorWithRed:0.88 green:0.88 blue:0.88 alpha:1.0]];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 22)];
    label.backgroundColor = [UIColor clearColor];
    [label setText:[self.sectionTitles objectAtIndex:(section - 1)]];
    [contentView addSubview:label];
    return contentView;
    }else{
        return nil;
    }
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if(tableView == _tableView1){
    NSMutableArray * existTitles = [NSMutableArray array];
    //section数组为空的title过滤掉，不显示
    for (int i = 0; i < [self.sectionTitles count]; i++) {
        if ([[self.dataSource1 objectAtIndex:i] count] > 0) {
            [existTitles addObject:[self.sectionTitles objectAtIndex:i]];
        }
    }
    return existTitles;
    }else{
        return nil;
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != actionSheet.cancelButtonIndex && _currentLongPressIndex) {
        MyBuddy *buddy = [[self.dataSource1 objectAtIndex:(_currentLongPressIndex.section - 1)] objectAtIndex:_currentLongPressIndex.row];
        [self hideHud];
        [self showHudInView:self.view hint:NSLocalizedString(@"wait", @"Pleae wait...")];
        
        __weak typeof(self) weakSelf = self;
        [[EaseMob sharedInstance].chatManager asyncBlockBuddy:buddy.buddy.username relationship:eRelationshipBoth withCompletion:^(NSString *username, EMError *error){
            typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf hideHud];
            if (!error)
            {
                //由于加入黑名单成功后会刷新黑名单，所以此处不需要再更改好友列表
            }
            else
            {
                [strongSelf showHint:error.description];
            }
        } onQueue:nil];
    }
    _currentLongPressIndex = nil;
}

#pragma mark - scrollView delegate
/*
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_slimeView scrollViewDidScroll];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [_slimeView scrollViewDidEndDraging];
}
 */

#pragma mark - slimeRefresh delegate
//刷新列表


#pragma mark - BaseTableCellDelegate

- (void)cellImageViewLongPressAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row >= 1) {
        // 群组，聊天室
        return;
    }
    NSDictionary *loginInfo = [[[EaseMob sharedInstance] chatManager] loginInfo];
    NSString *loginUsername = [loginInfo objectForKey:kSDKUsername];
    MyBuddy *buddy = [[self.dataSource1 objectAtIndex:(indexPath.section - 1)] objectAtIndex:indexPath.row];
    if ([buddy.buddy.username isEqualToString:loginUsername])
    {
        return;
    }
    
    _currentLongPressIndex = indexPath;
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", @"Cancel") destructiveButtonTitle:NSLocalizedString(@"friend.block", @"join the blacklist") otherButtonTitles:nil, nil];
    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
}

#pragma mark - private

- (NSMutableArray *)sortDataArray:(NSArray *)dataArray
{
    //建立索引的核心
    UILocalizedIndexedCollation *indexCollation = [UILocalizedIndexedCollation currentCollation];
    
    [self.sectionTitles removeAllObjects];
    [self.sectionTitles addObjectsFromArray:[indexCollation sectionTitles]];
    
    //返回27，是a－z和＃
    NSInteger highSection = [self.sectionTitles count];
    //tableView 会被分成27个section
    NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:highSection];
    for (int i = 0; i <= highSection; i++) {
        NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:1];
        [sortedArray addObject:sectionArray];
    }
    
    //名字分section
    for (MyBuddy *buddy in dataArray) {
        //getUserName是实现中文拼音检索的核心，见NameIndex类
//        NSString *firstLetter = [ChineseToPinyin pinyinFromChineseString:[[UserProfileManager sharedInstance] getNickNameWithUsername:buddy.nickname]];
        NSString *firstLetter = [ChineseToPinyin pinyinFromChineseString:buddy.nickname];
        NSInteger section = [indexCollation sectionForObject:[firstLetter substringToIndex:1] collationStringSelector:@selector(uppercaseString)];
        
        NSMutableArray *array = [sortedArray objectAtIndex:section];
        [array addObject:buddy];
    }
    
    //每个section内的数组排序
    for (int i = 0; i < [sortedArray count]; i++) {
        NSArray *array = [[sortedArray objectAtIndex:i] sortedArrayUsingComparator:^NSComparisonResult(MyBuddy *obj1, MyBuddy *obj2) {
//            NSString *firstLetter1 = [ChineseToPinyin pinyinFromChineseString:[[UserProfileManager sharedInstance] getNickNameWithUsername:obj1.username]];
            NSString *firstLetter1 = [ChineseToPinyin pinyinFromChineseString:obj1.nickname];
            firstLetter1 = [[firstLetter1 substringToIndex:1] uppercaseString];
            
//            NSString *firstLetter2 = [ChineseToPinyin pinyinFromChineseString:[[UserProfileManager sharedInstance] getNickNameWithUsername:obj2.username]];
            NSString *firstLetter2 = [ChineseToPinyin pinyinFromChineseString:obj2.nickname];
            firstLetter2 = [[firstLetter2 substringToIndex:1] uppercaseString];
            
            return [firstLetter1 caseInsensitiveCompare:firstLetter2];
        }];
        
        
        [sortedArray replaceObjectAtIndex:i withObject:[NSMutableArray arrayWithArray:array]];
    }
    
    return sortedArray;
}

#pragma mark - dataSource

- (void)reloadDataSource
{
    [self.dataSource1 removeAllObjects];
    [self.contactsSource removeAllObjects];
    
    NSArray *buddyList = [[EaseMob sharedInstance].chatManager buddyList];
    NSArray *blockList = [[EaseMob sharedInstance].chatManager blockedList];
    for (EMBuddy *buddy in buddyList) {
        if (![blockList containsObject:buddy.username]) {
//            [self.contactsSource addObject:buddy];
            MyBuddy *myBuddy = [MyBuddy new];
            myBuddy.buddy = buddy;
            [myBuddy loadInfoByUsername];
            [self.contactsSource addObject:myBuddy];
        }
    }
    
    NSDictionary *loginInfo = [[[EaseMob sharedInstance] chatManager] loginInfo];
    NSString *loginUsername = [loginInfo objectForKey:kSDKUsername];
    if (loginUsername && loginUsername.length > 0) {
        EMBuddy *loginBuddy = [EMBuddy buddyWithUsername:loginUsername];
//        [self.contactsSource addObject:loginBuddy];
        NSDictionary *info = [[Config Instance] getUInfo];
        MyBuddy *myBuddy = [MyBuddy new];
        myBuddy.buddy = loginBuddy;
        [myBuddy setInfoByDic:info];
        [self.contactsSource addObject:myBuddy];
    }
    
    [self.dataSource1 addObjectsFromArray:[self sortDataArray:self.contactsSource]];
    
    [_tableView1 reloadData];
}

#pragma mark - action

- (void)reloadApplyView
{
    NSInteger count = [[[ApplyViewController shareController] dataSource] count];
    
    if (count == 0) {
        self.unapplyCountLabel.hidden = YES;
    }
    else
    {
        NSString *tmpStr = [NSString stringWithFormat:@"%i", (int)count];
        CGSize size = [tmpStr sizeWithFont:self.unapplyCountLabel.font constrainedToSize:CGSizeMake(50, 20) lineBreakMode:NSLineBreakByWordWrapping];
        CGRect rect = self.unapplyCountLabel.frame;
        rect.size.width = size.width > 20 ? size.width : 20;
        self.unapplyCountLabel.text = tmpStr;
        self.unapplyCountLabel.frame = rect;
        self.unapplyCountLabel.hidden = NO;
    }
}

- (void)reloadGroupView
{
    [self reloadApplyView];
    
    if (_groupController) {
        [_groupController reloadDataSource];
    }
}

- (void)addFriendAction
{
    if([[Config Instance]isCookie]){
        AddFriendViewController *addController = [[AddFriendViewController alloc] initWithStyle:UITableViewStylePlain];
        addController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:addController animated:YES];
    }else{
        MyloginViewController *login = [MyloginViewController shareController];
        
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
    }
}

#pragma mark - EMChatManagerBuddyDelegate
- (void)didUpdateBlockedList:(NSArray *)blockedList
{
    [self reloadDataSource];
}


@end
